package com.xinke.edu.mypetadoption;

import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.xinke.edu.mypetadoption.databinding.ActivityMain3Binding;
import com.xinke.edu.mypetadoption.fragment3.SdFragment;
import com.xinke.edu.mypetadoption.fragment3.SjFragment;
import com.xinke.edu.mypetadoption.fragment3.ZzFragment;
import com.xinke.edu.mypetadoption.fragment3.SgFragment;

public class Main3Activity extends AppCompatActivity {

    private ActivityMain3Binding binding;

    private SjFragment sjFragment;
    private SdFragment sdFragment;
    private ZzFragment zzFragment;
    private SgFragment sgFragment;

    private Fragment activeFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMain3Binding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initFragments();

        binding.navgationview.setOnItemSelectedListener(item -> {
            int itemId = item.getItemId();
            Log.d("Main3Activity", "点击菜单ID: " + itemId);

            if (itemId == R.id.sju) {
                switchFragment(sjFragment);
                return true;
            } else if (itemId == R.id.sp) {
                switchFragment(sdFragment);
                return true;
            } else if (itemId == R.id.sja) {
                switchFragment(zzFragment);
                return true;
            } else if (itemId == R.id.dd) { // ✅ 新增菜单ID
                switchFragment(sgFragment);
                return true;
            }

            return false;
        });


    }

    private void initFragments() {
        sjFragment = new SjFragment();
        sdFragment = new SdFragment();
        zzFragment = new ZzFragment();
        sgFragment = new SgFragment();

        activeFragment = sjFragment;

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fragment, sjFragment, "SJ").show(sjFragment);   // 默认显示
        transaction.add(R.id.fragment, sdFragment, "SD").hide(sdFragment);
        transaction.add(R.id.fragment, zzFragment, "ZZ").hide(zzFragment);
        transaction.add(R.id.fragment, sgFragment, "SG").hide(sgFragment);
        transaction.commit();

        Log.d("Main3Activity", "默认显示 SjFragment");
    }

    private void switchFragment(Fragment fragment) {
        if (fragment == activeFragment) return;

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.hide(activeFragment).show(fragment).commitAllowingStateLoss();
        activeFragment = fragment;

        Log.d("Main3Activity", "切换到: " + fragment.getClass().getSimpleName());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}